import React, { useState, useEffect } from "react";
import { Card, Button, Select, Input, Table, message } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom"; // 导入 useNavigate
import {
  reqProducts,
  reqSearchProducts,
  reqUpdateProductStatus,
  reqDeleteProduct, // 新增导入删除商品的请求方法
} from "../../api";

const { Option } = Select;
const PAGE_SIZE = 4; // 默认显示的一页的条数

const ProductHome = () => {
  const navigate = useNavigate(); // 使用 useNavigate 获取 navigate 函数
  const [searchType, setSearchType] = useState("productName");
  const [searchName, setSearchName] = useState("");
  const [total, setTotal] = useState(0);
  const [products, setProducts] = useState([]);
  const [isSearch, setIsSearch] = useState(false);

  useEffect(() => {
    initColumns();
    getProducts(1);
  }, []);

  const initColumns = () => {
    return [
      {
        title: "商品名称",
        width: 100,
        dataIndex: "name",
      },
      {
        title: "商品描述",
        dataIndex: "desc",
      },
      {
        title: "价格",
        dataIndex: "price",
        render: (price) => `¥${price}`,
      },
      {
        title: "状态",
        render: (product) => (
          <span>
            <Button
              onClick={() =>
                updateProductStatus(product._id, product.status === 1 ? 0 : 1)
              }
            >
              {product.status === 1 ? "下架" : "上架"}
            </Button>
            <span style={{ marginLeft: 8 }}>
              {product.status === 1 ? "在售" : "已下架"}
            </span>
          </span>
        ),
      },
      {
        title: "操作",
        render: (product) => (
          <span>
            <Button type="link" onClick={() => handleDetail(product._id)}>
              详情
            </Button>
            <Button type="link" onClick={() => handleUpdate(product._id)}>
              修改
            </Button>
            <Button type="link" onClick={() => handleDelete(product._id)}>
              删除
            </Button>
          </span>
        ),
      },
    ];
  };

  const handleDetail = (productId) => {
    // 跳转详情页面
    navigate(`/products/product/detail/${productId}`);
  };

  const handleUpdate = (productId) => {
    // 跳转修改页面
    navigate(`/products/product/addupdate?productId=${productId}`);
  };

  const handleDelete = async (productId) => {
    try {
      const result = await reqDeleteProduct(productId);
      if (result.status === 0) {
        message.success("删除商品成功");
        // 删除成功后重新获取商品列表
        getProducts(1);
      } else {
        message.error(result.msg);
      }
    } catch (error) {
      console.error("删除商品异常", error);
      message.error("删除商品失败，请稍后重试");
    }
  };

  const getProducts = async (pageNum) => {
    try {
      let result;
      if (!isSearch) {
        result = await reqProducts(pageNum, PAGE_SIZE);
      } else {
        result = await reqSearchProducts({
          pageNum,
          pageSize: PAGE_SIZE,
          searchType,
          searchName,
        });
      }

      if (result.status === 0) {
        const { list, total } = result.data;
        setTotal(total);
        setProducts(list);
      }
    } catch (error) {
      console.error("获取商品列表失败", error);
      message.error("获取商品列表失败，请稍后重试");
    }
  };

  const handleSearch = () => {
    setIsSearch(true);
    getProducts(1);
  };

  const updateProductStatus = async (productId, status) => {
    try {
      const result = await reqUpdateProductStatus(productId, status);
      console.log("updateProductStatus result:", result);
      if (result.status === 0) {
        message.success("更新商品状态成功");
        // 更新成功后重新获取商品列表，并更新状态
        const updatedProducts = products.map((p) =>
          p._id === productId ? { ...p, status } : p
        );
        setProducts(updatedProducts);
      } else {
        message.error(result.msg);
      }
    } catch (error) {
      console.error("更新商品状态异常", error);
      message.error("更新商品状态失败，请稍后重试");
    }
  };

  const handleAddProduct = () => {
    // 跳转到添加商品页面
    navigate(`/products/product/addupdate`);
  };

  const title = (
    <span>
      <Select
        value={searchType}
        style={{ width: 200 }}
        onChange={(value) => setSearchType(value)}
      >
        <Option value="productName">按名称搜索</Option>
        <Option value="productDesc">按描述搜索</Option>
      </Select>
      <Input
        placeholder="关键字"
        style={{ width: 200, margin: "0 10px" }}
        value={searchName}
        onChange={(e) => setSearchName(e.target.value)}
      />
      <Button type="primary" onClick={handleSearch}>
        搜索
      </Button>
    </span>
  );

  const extra = (
    <Button type="primary" onClick={handleAddProduct}>
      <PlusOutlined /> 添加商品
    </Button>
  );

  return (
    <Card title={title} extra={extra}>
      <Table
        bordered
        columns={initColumns()}
        dataSource={products}
        rowKey="_id"
        pagination={{
          total,
          defaultPageSize: PAGE_SIZE,
          showQuickJumper: true,
          onChange: getProducts,
        }}
      />
    </Card>
  );
};

export default ProductHome;
